<?php
/*
 * 小傲
 * 订单api接口
 * 
 */
declare (strict_types = 1);

namespace app\api\controller;

use app\api\exception\ParamException;
use app\api\service\ApiResponse;
use app\api\service\StatusCode;
use think\exception\ValidateException;
use app\BaseController;
use app\api\validate\Orders as ValidateOrders;
use think\Request;
use app\api\model\SupplyOrders;
use Swoole\Coroutine\PostgreSQL;
use think\facade\Db;
use think\cache\driver\Redis;

class Orders extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index($num=5)
    {
        $allowFieds = ['intro','create_time'];
        $supply = SupplyOrders::where(['type'=>1,'status'=>1])
                    ->field($allowFieds)
                    ->limit($num)
                    ->select();
        $need = SupplyOrders::where(['type'=>2,'status'=>1])
                    ->field($allowFieds)
                    ->limit($num)
                    ->select();
        $arr = [
            'statusCode'=>200,
            'data'=>[
                'supply'=> $supply,
                'need'=>$need
                ]
        ];
        // return $arr;
        return ApiResponse::success($arr);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     */
    public function save(Request $request)
    {
        $validate = new ValidateOrders;
        $result =  $validate->check([
            'type'  => $request['type'],
            'intro' => $request['intro']
        ]);
        if ( !$result ) {
            throw new ParamException(400, $validate->getError());
        }


        Db::startTrans();
        try {
            $orders = new SupplyOrders();
            //订单
            $order_number = 'JS'.date('Ydm').time();
            $arr_order = [
                'type' => $request['type'],
                'order_number' => $order_number,
                'intro' => $request['intro']
            ];
            $apporders = $orders->save($arr_order);
            $id = $orders->id;
            if($apporders != true){
                throw new \Exception('插入数据失败！！！');
            }
            $redis = new Redis();
            $redis->set($order_number,time(),900);
            Db::commit();
            return ApiResponse::error(StatusCode::CREATED,"下单成功"); 
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiResponse::error(StatusCode::PARAM_ERROR,$e->getMessage()); 
        }

    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
